<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { ElButton, ElLink } from 'element-plus'
import { Table } from '@/components/Table'
import { useTable } from '@/hooks/web/useTable'
import { ViewData } from '@/api/types/userType'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { ref, unref, reactive } from 'vue'
import Edit from './components/Edit.vue'
import Detail from './components/Detail.vue'
import { useRouter } from 'vue-router'
import { useCache } from "@/hooks/web/useCache";
import { useAppStore } from "@/store/modules/app";

import api from '@/api'
defineOptions({
    name: 'teacherList'
})
const router = useRouter()
const { wsCache } = useCache();
const orgId = router.currentRoute.value.query.orgId;
const token = router.currentRoute.value.query.token;
const appStore = useAppStore();
wsCache.set(appStore.getUserToken, token);
const { getTeacherssDevice, deleteTeacherDevice, addTeacherDevice, modifyTeacherDevice } = api
const { register, tableObject, methods } = useTable<ViewData>({
    getListApi: (param) => getTeacherssDevice({ ...param, orgId }),
    delListApi: (param) => {
        return deleteTeacherDevice({ ids: param })
    },
    response: {
        list: 'content',
        total: 'totalElements'
    }
})

const orgList = ref([]);
const statusList = ref([]);
const channelList = ref([]);
const classesList = ref([]);
const { getList, setSearchParams } = methods
const crudSchemas = reactive<CrudSchema[]>([
    {
        width: "55px",
        field: 'index',
        label: '序号',
        type: 'index',
        form: {
            show: false
        },
        detail: {
            show: false
        }
    }, {
        field: 'name',
        label: '姓名',
        form: { colProps: { span: 12 } },
        search: { show: true },

    }, {
        field: 'sex',
        label: '性别',
        form: {
            colProps: { span: 12 },
            component: 'Select',
            componentProps: {
                options: [
                    { label: '男', value: '男' },
                    { label: '女', value: '女' }
                ]
            }
        },

    }, {
        field: 'age',
        label: '年龄',
        form: {
            colProps: { span: 12 },
            component: 'InputNumber'
        },

    }, {
        field: 'phone',
        label: '电话',
        form: { colProps: { span: 12 } },

    }, {
        field: 'inDate',
        label: '加入时间',
        form: {
            colProps: { span: 12 },
            component: 'DatePicker',
            componentProps: {
                type: 'date',
                valueFormat: 'YYYY-MM-DD'
            },
        }
    }, {
        field: 'homeAddress',
        label: '家庭住址',
        form: { colProps: { span: 24 } },

    }, {
        field: 'remark',
        label: '备注',
        form: {
            colProps: { span: 24 },
            component: 'Input',
            componentProps: {
                type: 'textarea',
                rows: 4
            },
        },

    },
    {
        field: 'action',
        fixed: 'right',
        width: '260px',
        label: '操作',
        form: { show: false },
        detail: { show: false }
    }
])

const { allSchemas } = useCrudSchemas(crudSchemas)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const pageLoad = async () => {
    getList()
}

pageLoad()

const AddAction = () => {
    dialogTitle.value = '添加'
    tableObject.currentRow = null
    actionType.value = 'add'
    dialogVisible.value = true

}
const delLoading = ref(false)
const delData = async (row: ViewData | null, multiple: boolean) => {
    tableObject.currentRow = row
    const { delList, getSelections } = methods
    const selections = await getSelections()
    delLoading.value = true
    await delList(
        multiple ? selections.map((v) => v.id) : [tableObject.currentRow?.id as string],
        multiple
    ).finally(() => {
        delLoading.value = false
    })
}
const actionType = ref('')

const action = (row: ViewData, type: string) => {
    dialogTitle.value = type === 'edit' ? '编辑' : '详情'
    actionType.value = type
    tableObject.currentRow = row
    dialogVisible.value = true

}

const writeRef = ref<ComponentRef<typeof Edit>>()
const loading = ref(false)

const save = async () => {
    const write = unref(writeRef)
    await write?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
            loading.value = true
            const data = (await write?.getFormData()) as ViewData
            data.orgId = orgId;
            let apiReques = data.id ? modifyTeacherDevice : addTeacherDevice
            const res = await apiReques(data)
                .catch(() => { })
                .finally(() => {
                    loading.value = false
                })
            if (res) {
                dialogVisible.value = false
                tableObject.currentPage = 1
                getList()
            }
        }
    })
}
const selectRow=(row)=>{
    location.href="http://select/name="+row.name;
}
</script>

<template>
    <ContentWrap>
        <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

        <div class="mb-10px">
            <ElButton type="primary" @click="AddAction">添加</ElButton>
            <ElButton :loading="delLoading" type="danger" @click="delData(null, true)">
                删除
            </ElButton>
        </div>

        <Table v-model:pageSize="tableObject.pageSize" v-model:currentPage="tableObject.currentPage"
            :columns="allSchemas.tableColumns" :data="tableObject.tableList" :loading="tableObject.loading" :pagination="{
                total: tableObject.total
            }" @register="register">
            <template #action="{ row }">
                <ElButton type="primary" @click="action(row, 'edit')"> 编辑 </ElButton>
                <ElButton type="danger" @click="delData(row, false)"> 删除 </ElButton>
                <ElButton type="warning" @click="selectRow(row)"> 选择 </ElButton>
            </template>
        </Table>
    </ContentWrap>

    <Dialog v-model="dialogVisible" :title="dialogTitle" max-height="420px" width="800px">
        <Edit v-if="actionType !== 'detail'" ref="writeRef" :form-schema="allSchemas.formSchema"
            :current-row="tableObject.currentRow" />

        <template #footer>
            <ElButton v-if="actionType !== 'detail'" type="primary" :loading="loading" @click="save">
                保存
            </ElButton>
            <ElButton @click="dialogVisible = false">关闭</ElButton>
        </template>
    </Dialog>
</template>
